// src/lib/axios.ts
import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  // InternalAxiosRequestConfig,
} from "axios";
import { message } from "antd";
import { BASE_URL } from "./env";
// import { md5, sortParams, isFileOrBlob } from "./utils"; // 需要补充这些工具函数

declare module "axios" {
  interface AxiosRequestConfig {
    showError?: boolean;
    errorMessage?: string;
  }
}

const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 10000,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });

  // 请求拦截器
  instance.interceptors.request
    .use
    // async () => {
    // 动态获取store
    // const store = await import("@/store").then((m) => m.default);
    // const state = store.getState();
    // // 添加认证信息
    // config.headers.Authorization = `${state?.app?.userInfo?.user_token}`;
    // // 参数处理逻辑
    // const params = config.data || config.params || {};
    // const isFormData = params instanceof FormData;
    // const sigParams: Record<string, any> = {};
    // // 处理不同参数类型
    // if (isFormData) {
    //   params.append("admin_user_id", state?.app?.userInfo?.admin_user_id);
    //   params.forEach((value, key) => {
    //     if (!isFileOrBlob(value)) {
    //       const replaceVal = value.toString().replace(/\r\n/g, "\n");
    //       sigParams[key] = replaceVal;
    //       params.set(key, replaceVal);
    //     }
    //   });
    //   params.append("sig", md5(sortParams(sigParams) + SIG));
    // } else {
    //   const processedParams = {
    //     ...params,
    //     admin_user_id: state?.app?.userInfo?.admin_user_id,
    //   };
    //   Object.keys(processedParams).forEach((key) => {
    //     if (typeof processedParams[key] === "string") {
    //       processedParams[key] = processedParams[key].replace(/\r\n/g, "\n");
    //     }
    //     sigParams[key] = processedParams[key];
    //   });
    //   processedParams.sig = md5(sortParams(sigParams) + SIG);
    //   // 根据请求方法分配参数位置
    //   if (
    //     ["post", "put", "patch", "delete"].includes(
    //       config.method?.toLowerCase() || ""
    //     )
    //   ) {
    //     config.data = processedParams;
    //   } else {
    //     config.params = processedParams;
    //   }
    // }
    // return config;
    // },
    // (error: AxiosError) => Promise.reject(error)
    ();

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      const { data } = response;
      const config = response.config;

      // 处理二进制响应
      if (config.responseType === "blob") {
        return response;
      }

      // 业务状态码处理
      if (data.code === 0) {
        return data.data;
      }

      // 特殊错误码处理
      if ([997].includes(data.code)) {
        message.error("Token无效了，请重新登录");
      } else if (config.showError !== false) {
        message.error(
          config.errorMessage ||
            `${data.msg || ""}-${data.error || ""}-${data.data?.msg}-【code:${
              data.code
            }】`
        );
      }

      return Promise.reject(data);
    },
    (error: AxiosError) => {
      const config = error.config || {};
      if (error.response) {
        switch (error.response.status) {
          case 401:
            message.error("认证失效，请重新登录");
            break;
          case 500:
            message.error("服务器内部错误");
            break;
          default:
            message.error(
              (config as AxiosRequestConfig).errorMessage || error.message
            );
        }
      }
      return Promise.reject(error);
    }
  );

  return instance;
};

const api = createAxiosInstance();

// 类型增强的请求方法
export const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<T> => {
  return api.request(config).then((res) => res.data);
};

// 保留原有请求方法
export const legacyRequest = async (
  url: string,
  params: object | FormData,
  method: "get" | "post" | "put" | "delete" | "patch"
) => {
  return api.request({
    url,
    method,
    data: ["post", "put", "patch"].includes(method.toLowerCase())
      ? params
      : undefined,
    params: ["get", "delete"].includes(method.toLowerCase())
      ? params
      : undefined,
  });
};

export default api;
